package com.bdqn.reflect;

import com.bdqn.reflect.pojo.Person;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Scanner;

/**
 * 测试6-调用方法
 *
 * @author LILIBO
 * @since 2024/6/27
 */
public class Test07Method {

    private static final Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("修改Person对象中的属性\n请输入属性名称：");
        String fieldName = input.next();
        try {
            // 获取Person类的Calss对象
            Class clazz = Person.class;
            // 通过反射的方式创建Person对象
            Person person = (Person) clazz.newInstance();
            // 通过属性对应的方法给属性设置值（例如：address）
            // 根据属性名称转换为对应的set方法名 Address
            fieldName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            String methodName = "set" + fieldName; // setAddress
            Method method = null; // clazz.getMethod(methodName, String.class);
            Method[] methods = clazz.getMethods();
            for (Method m : methods) {
                if (m.getName().equals(methodName) && m.getParameters().length == 1) {
                    method = m;
                    break;
                }
            }
            if (method == null) {
                System.out.println("未找到对应的set方法！");
                return;
            }
            method.setAccessible(true);
            System.out.println("请输入属性的值：");
            String fieldValue = input.next();
            // 此处编写你的代码..
            method.invoke(person, fieldValue);
            System.out.println("Person对象：" + person);
        } catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
            e.fillInStackTrace();
        }
    }

}
